package com.example.java.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class CustomProducerPartitions2 {
    public static void main(String[] args) {
        Properties properties = CustomProducerPartitions2.getKafkaProperties();
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        for (int i = 0; i < 5; i++) {
            kafkaProducer.send(new ProducerRecord<>("producer2", "a", "ni hao, i am producer2-a, send message " + i), (recordMetadata, exception) -> {
                if (exception == null) {
                    System.out.println("主题:" + recordMetadata.topic() + "->" + "key: a, 分区:" + recordMetadata.partition());
                }
            });
            kafkaProducer.send(new ProducerRecord<>("producer2", "b", "ni hao, i am producer2-b, send message " + i), (recordMetadata, exception) -> {
                if (exception == null) {
                    System.out.println("主题:" + recordMetadata.topic() + "->" + "key: b, 分区:" + recordMetadata.partition());
                }
            });
            kafkaProducer.send(new ProducerRecord<>("producer2", "f", "ni hao, i am producer2-f, send message " + i), (recordMetadata, exception) -> {
                if (exception == null) {
                    System.out.println("主题:" + recordMetadata.topic() + "->" + "key: f, 分区:" + recordMetadata.partition());
                }
            });
        }
        kafkaProducer.close();
        System.out.println("CustomProducerPartitions2 executed successfully");
    }

    private static Properties getKafkaProperties() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return properties;
    }
}